package client.main;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;

import client.mobile.Mobile;
import client.mobile.Player;
import client.mobile.PositionAsker;
import client.utility.PacketId.PacketID;
import client.view.Gui;


public abstract class Client {
	public static boolean loginRequest(String name,Gui gui, PacketID id) throws UnknownHostException, IOException{
		
		Socket socket = new Socket("localhost", 40404);
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		Writer writer = new Writer(socket.getOutputStream());
		
		writer.write(id,name);
		
		String line=reader.readLine();
		
		if(line.equals("user exists")){
			System.out.println("user already exists");
			return false;
		}
		else if(line.equals("user inexistend")){
			System.out.println("user inexistent");
			return false;
		}
		
		Player player = Player.constructFromString(line);
		
		if(player==null)
			return false;
		
		line=reader.readLine();
		
		while(line.length()>0){
			Mobile mob=Mobile.constructFromString(line);
			
			if(mob!=null && mob.getId()!=player.getId())
				player.add(mob);
			
			line=reader.readLine();
			
		}
		
		gui.setWriter(writer);
		gui.setPlayer(player);
		
		player.setWriter(writer);
		player.setReader(reader);
		
		Timer askerTimer = new Timer("mob move timer", false);
		askerTimer.scheduleAtFixedRate(new PositionAsker(player, gui), 45, 45);
		
		return true;
	}

}
